package pl.kaczmarz.audiosteganography;

public class Tools {

	public static boolean[] toBits(byte[] array) {
		boolean[] result = new boolean[array.length * 8];

		int i = 0;

		for (byte b : array) {
			for (int offset = 0; offset < 8; ++offset) {
				result[i++] = ((b & (1 << offset)) != 0);
			}
		}

		return result;
	}

	public static byte[] toBytes(boolean[] bits) {
		byte[] bytes = new byte[bits.length / 8];
		int pos = 0;
		int offset = 0;
		byte b = 0;

		for (boolean bit : bits) {
			if (bit) {
				b |= 1 << offset;
			}

			if (++offset == 8) {
				bytes[pos] = b;
				offset = 0;
				b = 0;
				++pos;
			}
		}

		return bytes;
	}

	public static double autoCorrelationSquares(int[] samples, int lag) {
		double acorr = 0;

		for (int i = 0; i < samples.length - lag; i++) {
			acorr += Math.pow(samples[i] - samples[i + lag], 2.0);
		}

		return acorr;
	}

	public static void autoCorrelationSquares(int[] samples, double[] output) {
//		double[] acorr = new double[samples.length];
		double max = 0;

		for (int lag = 0; lag < samples.length; ++lag) {
			output[lag] = autoCorrelationSquares(samples, lag);
			max = Math.max(max, output[lag]);
		}

		// normalize
		for (int i = 0; i < output.length; ++i) {
			output[i] /= max;
		}
	}

	public static double similarity(boolean[] a, boolean[] b) {
		int same = sameBits(a, b);
		int max = Math.min(a.length, b.length);

		return (double) same / max;
	}

	public static int sameBits(boolean[] a, boolean[] b) {
		int same = 0;
		int max = Math.min(a.length, b.length);

		for (int i = 0; i < max; ++i) {
			if (a[i] == b[i]) {
				++same;
			}
		}

		return same;
	}

	public static double similarity(byte[] a, byte[] b) {
		int same = sameBytes(a, b);
		int max = Math.min(a.length, b.length);

		return (double) same / max;
	}

	public static int sameBytes(byte[] a, byte[] b) {
		int same = 0;
		int max = Math.min(a.length, b.length);

		for (int i = 0; i < max; ++i) {
			if (a[i] == b[i]) {
				++same;
			}
		}

		return same;
	}
}
